package gob.pgr.util;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class PGRUtil {

	public static String generarXml(Object obj) {
		String xml = "";
		StringWriter stringWriter = new StringWriter();
		JAXBContext jaxbContext = null;
		try {
			jaxbContext = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "ISO-8859-1");
			marshaller.marshal(obj, stringWriter);
			xml = stringWriter.toString();
		} catch (Exception e) {
			System.err.println("Hubo un error");
			e.printStackTrace();
		}
		return xml;
	}
	
	public static Object leerXml(String xml, Class<?> clazz) {
		Object object = null;
		try {
			object = clazz.newInstance();
			JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			object = clazz.cast(unmarshaller.unmarshal(new StringReader(xml)));
		} catch (Exception e) {
			System.err.println("Hubo un error");
			e.printStackTrace();
		}
		return object;
	}
	
}
